//
//  WXPInputNewCardGetCodeView.m
//  MexicoLoan
//
//  Created by wxp on 2025/3/12.
//

#import "WXPInputNewCardGetCodeView.h"

@interface WXPInputNewCardGetCodeView ()<UITextFieldDelegate>

@end

@implementation WXPInputNewCardGetCodeView

#pragma mark - lazy
- (UIView *)backView{
    if (_backView == nil) {
        _backView = [UIView new];
        _backView.backgroundColor = COLOR_WHITE;
        _backView.width = SCREEN_WIDTH;
    }
    return _backView;
}
- (UILabel *)titleLabel{
    if (_titleLabel == nil) {
        _titleLabel = [UILabel new];
        _titleLabel.textColor = COLOR_BLACK;
        _titleLabel.font = [UIFont boldSystemFontOfSize:(18)];
        [_titleLabel fitTitle:@"Cuenta actual" variable:0];
    }
    return _titleLabel;
}
- (UIButton *)closeBtn{
    if (_closeBtn == nil) {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _closeBtn.tag = 1;
        [_closeBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_closeBtn setImage:[UIImage imageNamed:@"icon-login-close"] forState:UIControlStateNormal];
        _closeBtn.widthHeight = XY((16)+2*(20), (16)+2*(20));
    }
    return _closeBtn;
}
- (UIImageView *)imagePhone{
    if (!_imagePhone) {
        _imagePhone = [UIImageView new];
        _imagePhone.image = [UIImage imageNamed:@"icon-phone"];
        _imagePhone.widthHeight = XY(24, 24);
    }
    return _imagePhone;
}
- (UILabel *)phoneLabel{
    if (_phoneLabel == nil) {
        _phoneLabel = [UILabel new];
        _phoneLabel.textColor = COLOR_BLACK;
        _phoneLabel.font = [UIFont boldSystemFontOfSize:(18)];
    }
    return _phoneLabel;
}
- (UIView *)verificacionBackView{
    if (_verificacionBackView == nil) {
        _verificacionBackView = [UIView new];
        _verificacionBackView.backgroundColor = COLOR_WHITE;
        [GlobalMethod setRoundView:_verificacionBackView color:COLOR_LINE numRound:16 width:1];
        _verificacionBackView.userInteractionEnabled = true;
        [_verificacionBackView addSubview:self.verificacionTextField];
        [_verificacionBackView addSubview:self.codigoBtn];
        [_verificacionBackView addSubview:self.timeLabel];
    }
    return _verificacionBackView;
}

- (UITextField *)verificacionTextField{
    if (_verificacionTextField == nil) {
        _verificacionTextField = [UITextField new];
        _verificacionTextField.font = [UIFont systemFontOfSize:(16)];
        
        // 设置占位符
        NSString *placeholderText = @"Código de verificación";
        UIColor *placeholderColor = [UIColor lightGrayColor]; // 自定义颜色（例如浅灰色）
        NSDictionary *attributes = @{
            NSForegroundColorAttributeName: placeholderColor // 颜色属性
        };
        NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:attributes];
        _verificacionTextField.attributedPlaceholder = attributedPlaceholder;
        
        
        _verificacionTextField.borderStyle = UITextBorderStyleNone;
        _verificacionTextField.backgroundColor = [UIColor clearColor];
        _verificacionTextField.delegate = self;
        [_verificacionTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    }
    return _verificacionTextField;
}
- (UIButton *)codigoBtn{
    if (_codigoBtn == nil) {
        _codigoBtn = [UIButton  new];
        _codigoBtn.titleLabel.fontNum = (12);
        _codigoBtn.titleLabel.numberOfLines = 0;
        _codigoBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_codigoBtn setTitle:@"Conseguir ncódigo" forState:UIControlStateNormal];
        [_codigoBtn setTitleColor:COLOR_BLACK forState:UIControlStateNormal];
        [_codigoBtn sizeToFit];
        _codigoBtn.height = (45);
        _codigoBtn.tag = 2;
        [_codigoBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _codigoBtn;
}
- (UILabel *)timeLabel
{
    if (_timeLabel == nil) {
        _timeLabel = [UILabel  new];
        _timeLabel.fontNum = (16);
        _timeLabel.textColor = COLOR_BLACK;
        [_timeLabel fitTitle:@"60s" variable:0];
        _timeLabel.hidden = true;
    }
    return  _timeLabel;
}
- (UILabel *)errorLabel
{
    if (_errorLabel == nil) {
        _errorLabel = [UILabel  new];
        _errorLabel.textColor = COLOR_RED;
        _errorLabel.fontNum = (12);
        _errorLabel.numberOfLines = 0;
        _errorLabel.lineSpace = (2);
        _errorLabel.hidden = true;
    }
    return  _errorLabel;
}
- (UIButton *)enviarBtn{
    if (_enviarBtn == nil) {
        _enviarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _enviarBtn.tag = 3;
        [_enviarBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        _enviarBtn.backgroundColor = COLOR_PRIMARY;
        _enviarBtn.userInteractionEnabled = false;
        _enviarBtn.alpha = 0.5;
        [_enviarBtn setTitleColor:COLOR_BLACK forState:UIControlStateNormal];
        _enviarBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [GlobalMethod setRoundView:_enviarBtn color:[UIColor clearColor] numRound:BUTTON_HEIGHT/2 width:0];
        [_enviarBtn setTitle:@"confirmar" forState:(UIControlStateNormal)];
    }
    return _enviarBtn;
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT);
        self.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.4];
        [self addSubView];//添加子视图
    }
    return self;
}

//添加subview
- (void)addSubView{
    [self addSubview:self.backView];
    [self.backView addSubview:self.titleLabel];
    [self.backView addSubview:self.closeBtn];
    [self.backView addSubview:self.imagePhone];
    [self.backView addSubview:self.phoneLabel];
    [self.backView addSubview:self.verificacionBackView];
    [self.backView addSubview:self.errorLabel];
    [self.backView addSubview:self.enviarBtn];
    
    //初始化页面
    [self resetViewWithModel:nil];
}

#pragma mark - 点击事件
- (void)btnClick:(UIButton *)sender{
    [NSObject clickFeedback];
    [sender addClickAnimate];
    switch (sender.tag) {
        case 1:
        {
            [self removeFromSuperview];
            if (self.timer) {
                dispatch_source_cancel(self.timer);
                self.timer = nil;
            }
        }
            break;
        case 2:
        {
            if(self.blockSendSmsClick){
                self.blockSendSmsClick();
            }
        }
            break;
        case 3:
        {
            if(self.blockEnviarClick){
                self.blockEnviarClick();
            }
        }
            break;
            
        default:
            break;
    }
}

// 收键盘
// 点击界面空白区域 收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
}
// return键收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self endEditing:YES];
    return YES;
}

#pragma mark - 实现监听方法
- (void)textFieldDidChange:(UITextField *)textField{
    if(isStr(self.verificacionTextField.text)){
        self.enviarBtn.userInteractionEnabled = true;
        self.enviarBtn.alpha = 1;
    }else{
        self.enviarBtn.userInteractionEnabled = false;
        self.enviarBtn.alpha = 0.5;
    }
}

// 开始倒计时
- (void)startCountdown{
    if (self.timer != nil) {
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
    //倒计时时间
    __block NSInteger timeOut = 59;
    //建一个全局队列，默认优先级
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //每秒执行一次
    dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(self.timer, ^{
        
        //倒计时结束，关闭
        if (timeOut <= 0) {
            dispatch_source_cancel(self.timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.timeLabel.hidden = true;
                self.codigoBtn.hidden = false;
            });
        } else {
            int seconds = timeOut % 60;
            NSString *timeStr = [NSString stringWithFormat:@"%0.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.timeLabel fitTitle:[NSString stringWithFormat:@"%@s",timeStr] variable:0];
                self.timeLabel.rightCenterY = XY(self.timeLabel.right, self.timeLabel.centerY);
            });
            timeOut--;
        }
    });
    dispatch_resume(self.timer);
}

#pragma mark - 刷新view
- (void)resetViewWithModel:(id)model{
    self.closeBtn.rightTop = XY(self.backView.width, 0);
    self.titleLabel.leftTop = XY((20), (55));
    
    self.imagePhone.leftTop = XY(self.titleLabel.left, self.titleLabel.bottom+(36));
    
    [self.phoneLabel fitTitle:[NSString stringWithFormat:@"+52 %@",[GlobalData sharedInstance].Global_ModelUser.phone] variable:0];
    self.phoneLabel.leftCenterY = XY(self.imagePhone.right+10, self.imagePhone.centerY);
    
    self.verificacionBackView.widthHeight = XY(SCREEN_WIDTH-2*(20), Ratio(44));
    self.verificacionBackView.leftTop = XY(self.titleLabel.left, self.imagePhone.bottom+(30));
    
    self.codigoBtn.rightCenterY = XY(self.verificacionBackView.width-LEFT_MARDIN, self.verificacionBackView.height/2);
    
    self.verificacionTextField.widthHeight = XY(self.codigoBtn.left-2*LEFT_MARDIN, self.verificacionBackView.height-(12));
    self.verificacionTextField.leftCenterY = XY(LEFT_MARDIN, self.verificacionBackView.height/2);
    
    self.timeLabel.rightCenterY = XY(self.codigoBtn.right, self.codigoBtn.centerY);
    
    self.enviarBtn.widthHeight = XY(SCREEN_WIDTH - (40), BUTTON_HEIGHT);
    self.enviarBtn.leftTop = XY(self.titleLabel.left, self.verificacionBackView.bottom+(60));
    
    self.backView.height = self.enviarBtn.bottom+(66);
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.backView.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(16, 16)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = path.CGPath;
    self.backView.layer.mask = maskLayer;
    
    self.backView.leftBottom = XY(0, SCREEN_HEIGHT);
}

// 重置界面
- (void)resetViewAndTimer{
    if (self.timer) {
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
    self.timeLabel.hidden = true;
    self.codigoBtn.hidden = false;
    self.verificacionTextField.text = @"";
}

- (void)resetErrorLabelWithErrorStr:(NSString *)errorStr{
    self.errorLabel.hidden = false;
    [self.errorLabel fitTitle:readStr(errorStr) variable:SCREEN_WIDTH-2*self.titleLabel.left];
    self.errorLabel.leftTop = XY(self.titleLabel.left, self.verificacionBackView.bottom+(8));
    
    // 在3秒后执行某个操作
    double delayInSeconds = 3.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // 在这里执行您想要的操作
        self.errorLabel.hidden = true;
    });
}


@end
